package logic

import (
	"context"
	"errors"
	"weiyun-management-system/models/cache"
	"weiyun-management-system/models/mysql"
	"weiyun-management-system/pkg"

	"weiyun-management-system/weirpc/internal/svc"
	"weiyun-management-system/weirpc/weirpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *weirpc.UpdateRequest) (*weirpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	err := user.FindUseerbyId(mysql.DB, in.UserId)
	if err != nil {
		return nil, errors.New("当前用户不存在")
	}

	if pkg.Md5(in.OldPassword) != user.Password {
		return nil, errors.New("原密码输入错误")
	}
	if in.NewPassword != in.AckNewPassword {
		return nil, errors.New("两次密码输入不一致，请重新输入")
	}

	if in.NewPassword == in.OldPassword {
		return nil, errors.New("原密码和新密码输入重复,不允许修改")
	}
	result, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+user.Mobile).Result()
	if result != in.SmsCode {
		return nil, errors.New("短信验证码错误，请重新输入")
	}
	user.Password = pkg.Md5(in.NewPassword)
	err = user.UpdateUser(mysql.DB)
	if err != nil {
		return nil, errors.New("密码修改失败")
	}
	cache.Rdb.Del(cache.Ctx, "sendSms"+user.Mobile)
	return &weirpc.UpdateResponse{
		UserId: int64(user.ID),
	}, nil
}
